package cn.b504.qpcr.utils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class OSUtils {

  public static String getIdOfCPU() {
    //TODO: ProcessorId+MAC地址
    try {
      Process process = Runtime.getRuntime().exec(new String[]{"wmic", "cpu", "get", "ProcessorId"});
      process.getOutputStream().close();
      Scanner sc = new Scanner(process.getInputStream());
      sc.next();
      String serial = sc.next();
      sc.close();
      return serial;
    } catch (IOException e) {
      e.printStackTrace();
      return "";
    }
  }

  /**
   * SHA-1 散列
   *
   * @param data 字符串
   * @return hash 值
   */
  public static String hash(String data) {
    return hash(data, "SHA-1");
  }

  /**
   * SHA-224 散列
   *
   * @param data 字符串
   * @return hash 值
   */
  public static String hash224(String data) {
    return hash(data, "SHA-224");
  }

  /**
   * SHA-256 散列
   *
   * @param data 字符串
   * @return hash 值
   */
  public static String hash256(String data) {
    return hash(data, "SHA-256");
  }

  /**
   * 散列
   *
   * @param data      字符串
   * @param algorithm the name of the algorithm requested.
   *                  See the MessageDigest section in the <a href=
   *                  "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
   *                  Java Cryptography Architecture Standard Algorithm Name Documentation</a>
   *                  for information about standard algorithm names.
   * @return hash 值
   */
  public static String hash(String data, String algorithm) {
    MessageDigest instance;
    try {
      instance = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return "error";
    }
    instance.update(data.getBytes());
    byte[] digest = instance.digest();
    StringBuilder sb = new StringBuilder();
    for (byte b : digest) {
      sb.append(String.format("%X", b));
    }
    return sb.toString();
  }
}
